import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: () => import('../views/login/index.vue') },
  { path: '/register', component: () => import('../views/register/index.vue') },
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home', // 默认显示首页的二级路由
    children: [
      {
        path: '/home',
        component: () => import('@/views/home/index.vue')
      },
      { path: '/art-cate', component: () => import('@/views/article/ArticleCate.vue') },
      { path: '/art-list', component: () => import('@/views/article/ArticleList.vue') },
      { path: '/user', component: () => import('@/views/user/index.vue') },
      { path: '/user-avatar', component: () => import('@/views/user/UserAvatar.vue') },
      { path: '/user-info', component: () => import('@/views/user/UserInfo.vue') },
      { path: '/user-pwd', component: () => import('@/views/user/UserPwd.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  // 有token，去login就到主页  不是login就放行    没有token,看是否在白名单，不在就跳转登录
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/home')
    } else {
      next() // 放行
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // next('/login')
      router.push('/login')
    }
  }
})

export default router
